<?php
	define( 'DS', DIRECTORY_SEPARATOR );
	define( 'APP_PATH' , dirname( __FILE__ ) . DS );
	define( 'LIB_PATH', APP_PATH . 'lib' . DS );
	
	require( LIB_PATH . 'Requests.php' );
	Requests::register_autoloader();

	$headers = array(
		'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36',
		'Host' => 'www.oschina.net'
	);
	$data = array(
		'email' => 'light-li@hotmail.com',
		'pwd' => '40967e6632be015d82ca9f2d603bd8a00e53ba75', //密码使用sha1加密的，这里为了不暴露我的密码
		'save_login' => 1
	);
	$options = array(
		'verify' => false
	);
	
	//$session = new Requests_Session('https://www.oschina.net/action/user/hash_login', $headers, $options);
	
	$response = Requests::post('https://www.oschina.net/action/user/hash_login', $headers, $data, $options);

	//get the cookie
	$cookie_obj = $response->cookies->offsetGet('oscid');
	$osc_cookie = $cookie_obj->formatForHeader();

	$headers['Cookie'] = osc_cookie;//TODO::保存cookie，避免每次都登录。:),暂时无节操的这样吧
	
	//获取今天的天气 101090501 	
	$weather_url = array(
		'http://m.weather.com.cn/data/101090501.html',
		'http://m.weather.com.cn/data/101010100.html'
	);
	$weather_url = $weather_url[ mt_rand(0 ,1) ];
	
	$response = Requests::get($weather_url);
	$weather_info = json_decode($response->body, true);
	
	if( is_null($weather_info) ) {
		$msg = ':)昨天忘记看天气预报了！今天还在呆在家里吧！';
	}else {
		$weather_info = $weather_info['weatherinfo'];
		$msg[] = '今天是' . $weather_info['date_y'] . ',' . $weather_info['week'];
		$msg[] = '我在' . $weather_info['city'];
		$msg[] = '今天的温度有：' . $weather_info['temp1'];
		$msg[] = $weather_info['index_d'];
		$msg = implode(' ', $msg);
	}
	
	//$response = Requests::get('http://www.oschina.net', $headers, $options);
	//TODO::user_code和user通过分析网页获取或者其他途径
	$data = array(
		'user_code' => '71lcatTZqIuQ1CbPllOCROfjBKtQSrSS1u5PFfaD',
		'user' => 127088,
		'msg' => $msg
	);
	//send tweet
	//$response = Requests::post('http://www.oschina.net/action/tweet/pub', $headers, $data, $options);
	//TODO::表示Requests库真的没掌握:)
	$headers = array(
		'Accept:*/*',
		'Content-Type:application/x-www-form-urlencoded',
		'Cookie:' . $osc_cookie,
		'Host:www.oschina.net',
		'User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36',
		'X-Requested-With:XMLHttpRequest'
	);
	//print_r($response);
	$ch = curl_init();
	//判断是否https请求    
	curl_setopt($ch, CURLOPT_NOBODY, true);
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	curl_setopt($ch, CURLOPT_URL, 'http://www.oschina.net/action/tweet/pub');
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_HEADER, 0);//这里就不要header了,直接分析返回的json:)
	curl_setopt($ch, CURLOPT_TIMEOUT, 30);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));  
	
	$result = curl_exec($ch);
	echo $result;
	//parse $result
	$result = @json_decode( $result );
	if( is_null( $result ) ) {
		
	}else {
		
	}
	curl_close($ch);	
	